package com.gimi.cloud.bbp.client.common;

import javax.servlet.http.HttpServletResponse;


import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.JsonUtil;
import com.gimi.cloud.bbp.common.utils.reqhead.Response;
import com.gimi.cloud.bbp.common.utils.reqhead.Util;
import com.google.gson.JsonSyntaxException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;


/**
 * 全局异常处理类（当Controller种方法异常时，跳转到这里处理）
 * @author zhoufuhang
 * @time 2017年10月13日
 */
@ControllerAdvice
public class ExceptionHandle {
	private static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
	/**
	 * 注解@ExceptionHandler 填写需要处理的异常类型
	 * 如无对应处理机制则向上转型。
	 */
    @ExceptionHandler(MsgException.class)
    public void msgException(HttpServletResponse response, MsgException e) {  
    	try {
    		logger.info(e.getMessage());
			Response resp = new Response();
        	if(StringUtils.isNotBlank(e.getMsgCode())) {
        		resp.setResponseCode(e.getMsgCode(), e.getExceptionMsg());
			}else if (e.getExceptionMsg() != null) {
        		resp.setResponseCode(e.getMsgEnum(), e.getExceptionMsg());
        	} else {
        		resp.setResponseCode(e.getMsgEnum());
        	}
    		Util.sendResponse(JsonUtil.toJson(resp), response);
		} catch (Exception e2) {
			Response resp = new Response();
			resp.setResponseCode(ResponseCodeEnum.UNKNOWN_ERROR);
			Util.sendResponse(JsonUtil.toJson(resp), response);
		}
    }

	/**
	 * 全局异常捕获
	 * @param response
	 * @param e
	 */
    @ExceptionHandler(Exception.class)
    public void exception(HttpServletResponse response, Exception e) {
    	logger.error(e.getMessage(), e);
    	Response resp = new Response();
		resp.setResponseCode(ResponseCodeEnum.UNKNOWN_ERROR);
		Util.sendResponse(JsonUtil.toJson(resp), response);
    }

	/**
	 * JsonSyntaxException JSON校验捕获
	 * @param response
	 * @param e
	 */
	@ExceptionHandler(JsonSyntaxException.class)
    public void jsonSyntaxException(HttpServletResponse response, JsonSyntaxException e) {
    	logger.error(e.getMessage(), e);
    	Response resp = new Response();
		resp.setResponseCode(ResponseCodeEnum.PARAMETER_ERROR);
		Util.sendResponse(JsonUtil.toJson(resp), response);
    }  
}  